"""
模型工厂模块

根据配置自动选择合适的LLM模型
"""

import os
import logging
from typing import Any

logger = logging.getLogger(__name__)


def create_model(model_id: str = "deepseek-chat") -> Any:
    """
    创建LLM模型实例
    
    Args:
        model_id: 模型ID
        
    Returns:
        Any: 模型实例
    """
    try:
        # 检查可用的API密钥
        deepseek_key = os.getenv("DEEPSEEK_API_KEY")
        openai_key = os.getenv("OPENAI_API_KEY")
        
        # 优先使用DeepSeek
        if deepseek_key and deepseek_key != "your-deepseek-api-key":
            try:
                from agno.models.deepseek import DeepSeek
                logger.info(f"使用DeepSeek模型: {model_id}")
                return DeepSeek(id=model_id)
            except ImportError:
                logger.warning("DeepSeek模型不可用，尝试使用OpenAI")
        
        # 备用OpenAI
        if openai_key and openai_key != "your-openai-api-key":
            try:
                from agno.models.openai import OpenAIChat
                logger.info(f"使用OpenAI模型: {model_id}")
                return OpenAIChat(id=model_id)
            except ImportError:
                logger.warning("OpenAI模型不可用")
        
        # 如果都不可用，使用OpenAI作为默认（会在运行时报错，但至少能初始化）
        logger.warning("没有可用的API密钥，使用默认OpenAI模型（可能会在运行时失败）")
        from agno.models.openai import OpenAIChat
        return OpenAIChat(id=model_id)
        
    except Exception as e:
        logger.error(f"创建模型失败: {e}")
        # 最后的备用方案
        from agno.models.openai import OpenAIChat
        return OpenAIChat(id=model_id)


def get_recommended_model_id() -> str:
    """
    获取推荐的模型ID
    
    Returns:
        str: 推荐的模型ID
    """
    deepseek_key = os.getenv("DEEPSEEK_API_KEY")
    openai_key = os.getenv("OPENAI_API_KEY")
    
    if deepseek_key and deepseek_key != "your-deepseek-api-key":
        return "deepseek-chat"
    elif openai_key and openai_key != "your-openai-api-key":
        return "gpt-4o-mini"
    else:
        return "deepseek-chat"  # 默认返回deepseek
